import {
  Button,
  Card,
  Col,
  DatePicker,
  Form,
  Icon,
  Modal,
  Row,
  Spin,
  Tag,
  Typography,
  message,
} from 'antd'
import React, { useState } from 'react'
import { useAntdTable } from 'ahooks'
import { getTableData } from '../ProcessLogQuery/LogPage'
import { GlobalFormLayout } from '@/layouts/Form'
import request from '@/utils/request'
import Space from '@/components/Space'
import IconFont from '@/components/IconFont'
import SlickTable from '@/components/SlickTable'

const { RangePicker } = DatePicker
const { Text } = Typography

function ProcessLogCleanup({ form }) {
  const { getFieldDecorator, validateFields, getFieldsValue } = form
  const [loading, setLoading] = useState(false)

  const {
    tableProps: { pagination, ...restTableProps },
    refresh,
  } = useAntdTable(
    (query) => {
      const fieldsValue = getFieldsValue()
      const data = {
        ...fieldsValue,
        minStartTime: fieldsValue.startTimeRange[0].format('YYYY-MM-DD HH:mm:ss'),
        maxStartTime: fieldsValue.startTimeRange[1].format('YYYY-MM-DD HH:mm:ss'),
      }
      return getTableData({ ...query, ...data })
    },
    {
      defaultPageSize: 10,
      manual: true,
    },
  )

  const handleSubmit = () => {
    validateFields((err, values) => {
      if (err)
        return

      Modal.confirm({
        title: `你确定要清理这${pagination.total}条日志吗？`,
        content: (
          <>
            该操作属于危险操作，<Text type="danger">数据不可恢复</Text>，请提前做好备份！
          </>
        ),
        okType: 'danger',
        okText: '仍要删除',
        onOk() {
          setLoading(true)
          request('/processLog/cleanup', {
            data: {
              minStartTime: values.startTimeRange[0].format('YYYY-MM-DD HH:mm:ss'),
              maxStartTime: values.startTimeRange[1].format('YYYY-MM-DD HH:mm:ss'),
            },
          })
            .then(() => {
              message.success('清理成功')
              refresh()
            })
            .finally(() => {
              setLoading(false)
            })
        },
      })
    })
  }

  const handleQuery = () => {
    validateFields((err, values) => {
      if (!err)
        refresh()
    })
  }

  const columns = [
    {
      title: '流程名称',
      dataIndex: 'processName',
    },
    {
      title: '流程编码',
      dataIndex: 'processCode',
    },
    {
      title: '实例ID',
      dataIndex: 'instanceId',
    },
    {
      title: '扩展信息',
      dataIndex: 'extension',
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
    },
    {
      title: '异常描述信息',
      dataIndex: 'errorDesc',
    },
    {
      title: '执行状态',
      dataIndex: 'status',
      render: (status) => {
        switch (status) {
          case 0:
            return <Tag color="green">执行成功</Tag>
          case 1:
            return <Tag color="gold">业务异常</Tag>
          case 2:
            return <Tag color="volcano">程序异常</Tag>
          case 3:
            return <Tag color="magenta">网络异常</Tag>
          default:
            return ''
        }
      },
    },
  ]

  return (
    <Card title="流程日志清理" className="cute">
      <Form {...GlobalFormLayout} style={{ marginBottom: '16px' }}>
        <Row gutter={16}>
          <Col span={8}>
            <Form.Item label="开始时间">
              {getFieldDecorator('startTimeRange', {
                rules: [
                  {
                    required: true,
                    message: '时间范围不能为空',
                  },
                ],
              })(<RangePicker showTime={{ format: 'HH:mm:ss' }} style={{ width: '100%' }} />)}
            </Form.Item>
          </Col>
          <Col span={16}>
            <Space>
              <Button type="primary" onClick={handleQuery}>
                <Icon type="search" />
                查询
              </Button>
              <Button
                disabled={restTableProps.dataSource.length === 0}
                type="danger"
                loading={loading}
                onClick={handleSubmit}
              >
                <IconFont type="icon-cache" />
                清理
              </Button>
            </Space>
          </Col>
        </Row>
      </Form>
      <Spin spinning={loading}>
        <SlickTable
          rowKey="processLogId"
          columns={columns}
          data={{ pagination }}
          {...restTableProps}
        />
      </Spin>
    </Card>
  )
}

export default Form.create()(ProcessLogCleanup)
